<script setup>
import {
  Search
} from '@element-plus/icons-vue'
import { onMounted, ref } from 'vue'
import { getEmergencies, getEmergenciesApproved, addEmergency, approveEmergency } from '@/api/emergency'
import { ElMessage } from 'element-plus';
import { useTokenStore } from '@/stores/token';

const tokenStore = useTokenStore();

//搜索输入
const searchInput = ref('');

//分页条数据模型
const pageNum = ref(1)//当前页
const pageTotal = ref(20)//总条数
const pageSize = ref(3)//每页条数

//当每页条数发生了变化，调用此函数
const onSizeChange = async (size) => {
  pageSize.value = size
  await fetchEmergencies();
}
//当前页码发生变化，调用此函数
const onCurrentChange = async (num) => {
  pageNum.value = num
  await fetchEmergencies();
}

//应急信息列表数据模型
const emergencies = ref([
  {
    "informationId": 5,
    "title": "标题",
    "content": "内容",
    "publishTime": "2024-05-11 15:20:14",
    "isApproved": false
  }
])

const fetchEmergencies = async () => {
  try {
    let result = await getEmergencies();
    pageTotal.value = result.data.length;
    emergencies.value = result.data.slice((pageNum.value - 1) * pageSize.value, pageNum.value * pageSize.value);
  } catch (error) {
    console.error('获取应急信息列表失败：', error);
    ElMessage.error(result.data.message || '获取应急信息列表失败');
  }
};

onMounted(async () => {
  await fetchEmergencies();
});

const doSearch = async () => {
  const keyword = input.value.trim(); // 转换为小写并去除首尾空格
  if (!keyword) {
    await fetchEmergencies(); // 如果搜索关键词为空，则显示所有列表
    return; // 如果搜索关键词为空，直接返回，不执行后续操作
  }
  let result = await getEmergencies(); // 获取列表
  try {
    // 根据id进行模糊搜索
    pageTotal.value = result.data.data.filter(e =>
      e.informationId.includes(keyword)
    ).length;
    complaints.value = result.data.data.filter(e =>
      e.informationId.includes(keyword)
    );
  } catch (error) {
    console.error('搜索时出错：', error);
    ElMessage.error(result.data.message || '搜索时出错');
  }
  input.value = ''; // 清空输入框
};

const isApprovedFilters = ref([
  { text: '未审批', value: 0 },
  { text: '已审批', value: 1 },
]);

const filterTag = (value, row) => {
  return row.isApproved === value;
};

const doApproveEmergency = async (row) => {
  if (tokenStore.getAuth() !== 4) {
    ElMessage.error('你没有权限进行审批操作');
    return;
  }

  // 处理审批逻辑
  let result = await approveEmergency(row.informationId);
  console.log(result);
  if (result.code === 0) {
    ElMessage.success('审批应急信息成功');
    fetchEmergencies();
  } else {
    ElMessage.error(result.data.message || '审批应急信息失败');
  }
};

const doAddEmergency = () => {
  if (tokenStore.getAuth() !== 1) {
    ElMessage.error('你没有权限进行新增操作');
    return;
  }

  // 打开新增应急信息弹窗
  drawerVisible.value = true;
};

const drawerVisible = ref(false); // 抽屉是否可见

const emergencyModel = ref({
  title: '',
  content: '',
  publishTime: ''
});
const emergencyRules = {
  title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
  content: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
  publishTime: [{ required: true, message: '发布日期不能为空', trigger: 'blur' }]
}

const submitEmergency = async () => {
  try {
    let result = await addEmergency(emergencyModel.value);
    console.log(result);
    if (result.code === 0) {
      ElMessage.success('新增应急信息成功');
      drawerVisible.value = false;
      await fetchEmergencies();
    } else {
      ElMessage.error(result.data.message || '新增应急信息失败');
    }
  } catch (error) {
    console.error('新增应急信息失败：', error);
    ElMessage.error('新增应急信息失败');
  }
};

</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>应急信息管理</span>
      </div>
    </template>

    <div class="toolbar">
      <!-- 搜索表单 -->
      <el-form inline class="toolbar-form">
        <el-form-item>
          <el-input v-model="searchInput" style="width: 240px" placeholder="请输入应急信息ID" clearabl :prefix-icon="Search" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="doSearch">搜索</el-button>
        </el-form-item>
      </el-form>
      <!-- 新增按钮 -->
      <el-button type="primary" @click="doAddEmergency">新增</el-button>
    </div>


    <!-- 投诉列表 -->
    <el-table :data="emergencies" style="width: 100%">
      <el-table-column type="selection" width="55" />
      <el-table-column label="应急信息ID" prop="informationId" width="200" />
      <el-table-column label="标题" width="400" prop="title"></el-table-column>
      <el-table-column label="内容" prop="content"></el-table-column>
      <el-table-column label="发布时间" prop="publishTime"></el-table-column>
      <el-table-column prop="isApproved" label="审批状态" width="100" :filters="isApprovedFilters"
        :filter-method="filterTag" filter-placement="bottom-end">
        <template #default="scope">
          <el-tag :type="scope.row.isApproved ? 'success' : 'info'" disable-transitions>
            {{ scope.row.isApproved ? '已审批' : '未审批' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button plain type="primary" :disabled="row.isApproved" @click="doApproveEmergency(row)">审批</el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="暂无数据" />
      </template>
    </el-table>

    <!-- 抽屉 -->
    <el-drawer title="新增应急信息" v-model="drawerVisible" width="300px" direction="rtl">
      <el-form :model="emergencyModel" :rules="emergencyRules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="emergencyModel.title"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input v-model="emergencyModel.content" type="textarea" :autosize="{ minRows: 10 }"></el-input>
        </el-form-item>
        <el-form-item label="发布日期" prop="publishTime">
          <el-date-picker v-model="emergencyModel.publishTime" type="datetime" placeholder="Pick a Date"
            format="YYYY/MM/DD HH:mm:ss" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div style="text-align: right;">
          <el-button @click="drawerVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEmergency">提交</el-button>
        </div>
      </template>
    </el-drawer>

    <!-- 分页条 -->
    <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[3, 5, 10, 15]"
      layout="jumper, total, sizes, prev, pager, next" background :total="pageTotal" @size-change="onSizeChange"
      @current-change="onCurrentChange" style="margin-top: 20px;
        justify-content: flex-end" />
  </el-card>
</template>

<style scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}

/* 抽屉样式 */
.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }

    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }

    .el-upload:hover {
      border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}

.editor {
  width: 100%;

  :deep(.ql-editor) {
    min-height: 200px;
  }
}

.toolbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}
</style>